package easy;

/**
 * Created by daodao on 2017/12/1.
 * Problem 38
 * Description: The count-and-say sequence is the sequence of integers with the first five terms as following:
 *              1.     1
 *              2.     11
 *              3.     21
 *              4.     1211
 *              5.     111221
 * 1 is read off as "one 1" or 11.
 * 11 is read off as "two 1s" or 21.
 * 21 is read off as "one 2, then one 1" or 1211.
 * Given an integer n, generate the nth term of the count-and-say sequence.
 *
 * Note: Each term of the sequence of integers will be represented as a string.
 *
 * Example 1: Input: 1
 *            Output: "1"
 * Exqmple 2: Input: 4
 *            Output: "1211"
 */
public class CountAndSay {
    public static String countAndSay(int n) {
        String result = "1";
        for (int i = 2; i <= n; i++) {
            result = generateStr(result);
        }
        return result;
    }
    public static String generateStr(String src) {
        char[] chars = src.toCharArray();
        StringBuilder dst = new StringBuilder();
        int count = 0;
        char cur;
        for (int i = 0; i< chars.length;) {
            cur = chars[i];
            while (i < chars.length && chars[i] == cur) {
                count++;
                i++;
            }
            dst.append(count).append(cur);
            count = 0;
        }
        return dst.toString();
    }
}
